package com.qf.cx.simplenms.core.spi.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.qf.cx.simplenms.core.spi.Updater;
import com.qf.cx.simplenms.persist.entity.ReaderGroupEntity;
import com.qf.cx.simplenms.persist.entity.TagMemoryEntity;
import com.qf.cx.simplenms.persist.entity.TopicEntity;
import com.qf.cx.simplenms.persist.service.api.TopicService;
import com.qf.cx.simplenms.readergroup.api.ReaderGroup;
import com.qf.cx.simplenms.readergroup.api.ReaderGroupManager;
import com.qf.cx.simplenms.tagmemory.api.TagMemoryManager;
import com.qf.cx.simplenms.tagmemory.model.TagMemoryModel;
import com.qf.cx.simplenms.topic.api.TopicManager;
import com.qf.cx.simplenms.topic.model.TopicModel;

public class TopicUpdater implements Updater {
	@Autowired
	private TopicService topicService;
	@Autowired
	private TopicManager topicManager;
	@Autowired
	private ReaderGroupManager readerGroupManager;
	@Autowired
	private TagMemoryManager tagMemoryManager;

	@Override
	public void update() {
		List<TopicEntity> topicEntities = topicService.getTopics();
		List<TopicModel> list = new ArrayList<>();

		for (TopicEntity topicEntity : topicEntities) {
			TopicModel topicModel = new TopicModel();
			topicModel.setName(topicEntity.getName());
			topicModel.setCycle(topicEntity.getCycle());

			Set<ReaderGroup> readerGroups = new HashSet<>();
			for (ReaderGroupEntity each : topicEntity.getReaderGroupEntities()) {
				ReaderGroup readerGroup = readerGroupManager.getReaderGroup(each.getName());
				if (readerGroup != null) {
					readerGroups.add(readerGroup);
				}
			}

			topicModel.addReaderGroups(readerGroups);

			Set<TagMemoryModel> tagMemories = new HashSet<>();
			for (TagMemoryEntity each : topicEntity.getTagMemoryEntities()) {
				TagMemoryModel tagMemory = tagMemoryManager.getTagMemory(each.getName());
				if (tagMemory != null) {
					tagMemories.add(tagMemory);
				}
			}
			topicModel.addTagMemories(tagMemories);
			list.add(topicModel);
		}
		topicManager.updateCache(list);
	}

}
